using UnityEngine;
using System.Collections;

public class Environment : MonoBehaviour {

	public Transform player;
	public AudioSource heartSound;
	public float dangerRange = 5f;
	public float killingRange = 2f;

	public AudioSource barking;
	public AudioSource noise1;
	public AudioSource noise2;
	public AudioSource noise3;

	AudioMovement audioScript;
	PlayerMovement playerScript;

	// Use this for initialization
	void Start () {
		audioScript = GameObject.FindObjectOfType(typeof(AudioMovement)) as AudioMovement;
		playerScript = GameObject.FindObjectOfType(typeof(PlayerMovement)) as PlayerMovement;
	}
	
	// Update is called once per frame
	void Update () {
		Transform nearest = null;
		float nearestDist = 10000f;
		foreach (Transform child in transform)
		{
			if (nearest == null)
			{
				nearest = child;
				nearestDist = Vector3.Distance(player.position, child.position);
				continue;
			}

			float dist = Vector3.Distance(player.position, child.position);
			if ( dist < nearestDist)
			{
				nearest = child;
				nearestDist = dist;
			}
		}

		float t = (nearestDist - killingRange) / (nearest.audio.maxDistance - 7);
		heartSound.volume = Mathf.Lerp(0.0f, 0.25f, 1 - t);
		heartSound.pitch = Mathf.Lerp(0.7f, 1.2f, 1 - t);

		//Debug.Log("distance: " + nearestDist);
		if (nearestDist < dangerRange)
		{
			if (!playerScript.isInDanger())
			{
				audioScript.SetActiveLines("danger");
				playerScript.EnterDanger();
			}
		}
		else if (playerScript.isInDanger())
			playerScript.ExitDanger();

		if (nearestDist < killingRange)
			playerScript.Kill();
	}

	void PlaySound(AudioSource src)
	{
		if (!src.isPlaying)
			src.Play();
	}
}
